//
//  CABasicAnimationViewController.m
//  CoreAnimation
//
//  Created by 张国文 on 16/10/26.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "CABasicAnimationViewController.h"

@interface CABasicAnimationViewController ()<CAAnimationDelegate>

@property (nonatomic, strong) UIView *backgroundView;

@property (nonatomic, strong) CALayer *colorLayer;

@end

@implementation CABasicAnimationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.backgroundView = [[UIView alloc] initWithFrame:self.view.frame];
    self.backgroundView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5];
    [self.view addSubview:_backgroundView];
    
    self.colorLayer = [CALayer layer];
    self.colorLayer.frame = CGRectMake(100, 50, 100, 100);
    self.colorLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.backgroundView.layer addSublayer:_colorLayer];
    
    UIButton *changeColor = [UIButton buttonWithType:UIButtonTypeCustom];
    changeColor.frame = CGRectMake(50, 400, 150, 30);
    [changeColor setTitle:@"改变颜色" forState:UIControlStateNormal];
    [changeColor setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [changeColor addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:changeColor];
}

- (void)change:(UIButton *)btton
{
    CGFloat red = arc4random() % 256 / 255.0;
    CGFloat green = arc4random() % 256 / 255.0;
    CGFloat blue = arc4random() % 256 / 255.0;
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"backgroundColor";
    animation.toValue = (__bridge id _Nullable)([UIColor colorWithRed:red green:green blue:blue alpha:1].CGColor)
    ;
//    animation.removedOnCompletion = NO;
//    animation.fillMode = kCAFillModeForwards; // 这两句是保留最后的状态
    animation.duration = 1;
    animation.delegate = self;
    [self.colorLayer addAnimation:animation forKey:@"123"];
    
}


- (void)animationDidStop:(CABasicAnimation *)anim finished:(BOOL)flag
{
    // 如果不用animation的保留最后状态的属性，我们只能在代理方法里面更改状态，以保持最后状态
    //set the backgroundColor property to match animation toValue
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    self.colorLayer.backgroundColor = (__bridge CGColorRef)anim.toValue;
    [CATransaction commit];
}

@end
